package com.shp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shp.pojo.*;
import com.shp.service.*;
import com.shp.utils.CheckCodeUtil;
import com.shp.utils.DeleteFileUtil;
import com.shp.utils.IpUtil;
import com.shp.utils.OnlineUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Description:
 * 管理员控制器
 *
 * @author zwl
 * @version 1.0
 * @date 2020/3/15 18:30
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PurseService purseService;

    /**
     * 跳转到登录页面
     *
     * @return "admin/login"
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 登陆验证
     *
     * @param admin   登陆信息
     * @param session HttpSession
     * @return ResultInfo
     */
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo checkLogin(Admin admin, HttpSession session) {
        return adminService.checkLogin(new ResultInfo(), session, admin);
    }

    /**
     * 获取生成验证码显示到界面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) {
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        try {
            //输出图片方法
            CheckCodeUtil.getCheckCode(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到管理页面
     *
     * @return "admin/main"
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String mainPage(Model model, HttpSession session) {
        // 获取今日的新增信息
        NewsSize news = newsService.getNewsSize(1, 1, 1, 1);
        model.addAttribute("news", news);
        return "admin/main";
    }

    /**
     * 获取管理员的姓名
     *
     * @return username
     */
    @RequestMapping(value = "/activeUser", method = RequestMethod.POST)
    @ResponseBody
    public Admin activeUser(HttpSession session) {
        // 获取用户的信息
        Admin admin = (Admin) session.getAttribute("admin");
        Integer adminId = admin.getId();
        return adminService.getAdmin(adminId);
    }

    /**
     * 退出登陆
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String out(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        String username = admin.getUsername();
        OnlineUserUtil.reduceSession(username);
        OnlineUserUtil.removeUserEmail(username);
        // 重定向到登陆页面
        return "redirect:admin/login";
    }

    /**
     * 查询所有用户
     *
     * @return "admin/user_list"
     */
    @RequestMapping(value = "/userpage/{pageNum}", method = RequestMethod.GET)
    public String userList(@PathVariable(value = "pageNum", required = true) Integer pageNum, Model model) {
        // 定义每页显示的记录数
        int pageSize = 10;

        List<User> userList = null;
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        userList = userService.getAll();
        // 参数：结果集合，连续要显示的页数
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        return "admin/user_list";
    }

    /**
     * 查询用户
     *
     * @return User
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(Integer id) {
        // 获取用户的id
        if (id != null) {
            // 查询指定id的User
            return userService.getUserById(id);
        }
        return null;
    }

    /**
     * 修改用户
     *
     * @param user User
     * @return ResultInfo
     */
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo updateUser(@RequestBody User user) {
        boolean flag = userService.updateUser(user);
        ResultInfo info = new ResultInfo();
        if (flag) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 分页条件查询用户
     *
     * @param user    查询条件
     * @param pageNum 页码
     * @param model   Model
     * @return "admin/user_list"
     */
    @RequestMapping(value = "/user/select/{pageNum}", method = RequestMethod.GET)
    public String selectedUser(User user, @PathVariable(value = "pageNum", required = true) Integer pageNum, Model model) {
        // 定义每页显示的记录数
        int pageSize = 10;
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的user
        List<User> userList = userService.getUserBySelect(user);
        // 参数：结果集合，连续要显示的页数
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("preSelect", user);
        return "admin/user_list";
    }

    /**
     * 删除用户
     *
     * @return ResultInfo
     */
    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    @ResponseBody
    public ResultInfo deleteUser(@RequestBody Integer[] ids) {
        ResultInfo info = new ResultInfo();
        // 删除用户
        if (userService.deleteUser(ids)) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 查询所有商品，分页
     *
     * @param model   Model
     * @param pageNum 页码
     * @return "admin/goods_list"
     */
    @RequestMapping(value = "/goodspage/{pageNum}", method = RequestMethod.GET)
    public String getGoodsList(Model model, @PathVariable(value = "pageNum", required = true) Integer pageNum) {
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        List<Good> goodsList = goodsService.getAll();
        // 参数：结果集合，连续要显示的页数
        PageInfo<Good> pageInfo = new PageInfo<Good>(goodsList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        return "admin/goods_list";
    }

    /**
     * 查询商品的具体信息
     *
     * @param id 商品id
     * @return Good
     */
    @RequestMapping(value = "/goods", method = RequestMethod.GET)
    @ResponseBody
    public Good getGoods(Integer id) {
        if (id != null) {
            return goodsService.getGoodsByGoodsId(id);
        }
        return null;
    }

    /**
     * 修改商品信息
     *
     * @param goods
     * @return
     */
    @RequestMapping(value = "/goods", method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo updateGoods(@RequestBody Good goods) {
        boolean flag = goodsService.updateGoods(goods);
        ResultInfo info = new ResultInfo();
        if (flag) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 删除商品
     *
     * @param ids 商品id数组
     * @return ResultInfo
     */
    @RequestMapping(value = "/goods", method = RequestMethod.DELETE)
    @ResponseBody
    public ResultInfo deleteGoods(@RequestBody Integer[] ids) {
        ResultInfo info = new ResultInfo();
        // 获取商品图片名
        List<String> images = goodsService.getGoodsImages(ids);
        if (goodsService.deleteGoodsBatch(ids)) {
            // 删除商品的图片
            DeleteFileUtil.deleteImages(images);
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 分页条件查询商品
     *
     * @param goods 查询条件
     * @param model Model
     * @return "admin/goods_list"
     */
    @RequestMapping(value = "/goods/select/{pageNum}", method = RequestMethod.GET)
    public String getGoodsSelect(Good goods, Model model, @PathVariable("pageNum") Integer pageNum) {
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的goods
        List<Good> goodsList = goodsService.getGoodsBySelect(goods);
        // 参数：结果集合，连续要显示的页数
        PageInfo<Good> pageInfo = new PageInfo<Good>(goodsList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("preSelect", goods);
        return "admin/goods_list";
    }


    /**
     * 分页查询订单
     *
     * @param pageNum 页码
     * @param model   订单数据
     * @return
     */
    @RequestMapping(value = "/orderspage/{pageNum}", method = RequestMethod.GET)
    public String getOrdersList(@PathVariable(value = "pageNum", required = true) Integer pageNum, Model model) {
        // 定义查询的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Orders> ordersList = ordersService.getAll();
        PageInfo<Orders> info = new PageInfo<Orders>(ordersList);
        model.addAttribute("info", info);
        return "admin/order_list";
    }

    /**
     * 查看订单信息
     *
     * @param id 订单编号
     * @return 订单信息
     */
    @RequestMapping(value = "/order", method = RequestMethod.GET)
    @ResponseBody
    public Orders getOrdersById(Integer id) {
        if (id != null) {
            // 查询
            return ordersService.getOrders(id);
        }
        return null;
    }

    /**
     * 修改订单信息
     *
     * @param orders
     * @return
     */
    @RequestMapping(value = "/order", method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo updateOrder(@RequestBody Orders orders) {
        boolean flag = ordersService.updateOrder(orders);
        ResultInfo info = new ResultInfo();
        if (flag) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 分页条件查询订单
     *
     * @param pageNum
     * @param model
     * @param orders
     * @return
     */
    @RequestMapping(value = "/order/select/{pageNum}", method = RequestMethod.GET)
    public String getOrderSelect(@PathVariable(value = "pageNum", required = true) Integer pageNum, Model model, Orders orders) {
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的goods
        List<Orders> ordersList = ordersService.getOrdersBySelected(orders);
        // 参数：结果集合，连续要显示的页数
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(ordersList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("preSelect", orders);
        return "admin/order_list";
    }

    /**
     * 批量删除订单
     *
     * @param ids 订单id
     * @return
     */
    @RequestMapping(value = "/order")
    @ResponseBody
    public ResultInfo deleteOrders(@RequestBody Integer[] ids) {
        ResultInfo info = new ResultInfo();
        // 删除订单
        if (ordersService.deleteOrdersBatch(ids)) {
            info.setFlag(true);
        }
        return info;
    }


    /**
     * 钱包分页
     *
     * @param model
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/purse/page/{pageNum}")
    public String getUserOrders(Model model, @PathVariable Integer pageNum) {
        // 定义查询的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Purse> purseList = purseService.getAll();
        PageInfo<Purse> info = new PageInfo<Purse>(purseList);
        model.addAttribute("info", info);
        return "admin/purse_list";
    }

    @RequestMapping(value = "/purse", method = RequestMethod.GET)
    @ResponseBody
    public Purse getPurse(Integer id) {
        if (id != null) {
            return purseService.getPurseById(id);
        }
        return null;
    }

    @RequestMapping(value = "/purse", method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo updatePurse(@RequestBody Purse purse) {
        ResultInfo info = new ResultInfo();
        if (purseService.update(purse)) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 钱包选择分页
     * @param email
     * @param status
     * @param model
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/purse/select/{pageNum}",method = RequestMethod.GET)
    public String getSelectedPurse(String email, Integer status, Model model, @PathVariable Integer pageNum) {
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的
        List<Purse> purseList = purseService.getSelectedPurse(email,status);
        // 参数：结果集合，连续要显示的页数
        PageInfo<Purse> pageInfo = new PageInfo<Purse>(purseList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("email", email);
        model.addAttribute("status",status);
        return "admin/purse_list";
    }

    /**
     * 提现列表分页
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/withdrawals/page/{pageNum}",method = RequestMethod.GET)
    public String getWithdrawalsList(@PathVariable Integer pageNum,Model model){
        // 定义查询的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Withdrawals> withdrawalsList = purseService.getWithdrawalsAll();
        PageInfo<Withdrawals> info = new PageInfo<Withdrawals>(withdrawalsList);
        model.addAttribute("info", info);
        return "admin/withdrawals_list";
    }

    /**
     * 提现审核
     * @param withdrawals
     * @return
     */
    @RequestMapping(value = "/withdrawals",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo checkWithdrawals(@RequestBody Withdrawals withdrawals){
        if( withdrawals == null ||withdrawals.getId() == null || withdrawals.getStatus() == null || withdrawals.getUser_id() == null){
            return null;
        }
        ResultInfo info = new ResultInfo();
        if(purseService.withdrawalsPass(withdrawals)){
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 提现选择分页
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/withdrawals/select/{pageNum}",method = RequestMethod.GET)
    public String getSelectedWithdrawals(@PathVariable Integer pageNum,Model model,String email,Byte status){
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的
        List<Withdrawals> withdrawalsList = purseService.getSelectedWithdrawals(email,status);
        // 参数：结果集合，连续要显示的页数
        PageInfo<Withdrawals> pageInfo = new PageInfo<Withdrawals>(withdrawalsList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("_email", email);
        model.addAttribute("_status",status);
        return "admin/withdrawals_list";
    }

    /**
     * 批量删除提现记录
     * @param ids id列表
     * @return ResultInfo
     */
    @RequestMapping(value = "/withdrawals",method = RequestMethod.DELETE)
    @ResponseBody
    public ResultInfo deleteWithdrawalsBatch(@RequestBody Integer[] ids){
        ResultInfo info = new ResultInfo();
        // 删除
        if (purseService.deleteWithdrawalsBatch(ids)) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 充值列表分页
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/recharge/page/{pageNum}",method = RequestMethod.GET)
    public String getRechargeList(@PathVariable Integer pageNum,Model model){
        // 定义查询的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Recharge> rechargeList = purseService.getRechargeAll();
        PageInfo<Recharge> info = new PageInfo<Recharge>(rechargeList);
        model.addAttribute("info", info);
        return "admin/recharge_list";
    }

    /**
     * 充值审核
     * @param recharge
     * @return
     */
    @RequestMapping(value = "/recharge",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo checkWithdrawals(@RequestBody Recharge recharge){
        if( recharge == null ||recharge.getId() == null || recharge.getStatus() == null || recharge.getUser_id() == null){
            return null;
        }
        ResultInfo info = new ResultInfo();
        if(purseService.rechargePass(recharge)){
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 提现选择分页
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/recharge/select/{pageNum}",method = RequestMethod.GET)
    public String getSelectedRecharge(@PathVariable Integer pageNum,Model model,String email,Byte status){
        // 定义每页显示的记录数
        int pageSize = 10;
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        // 获取第pageNum页，pageSize条内容
        PageHelper.startPage(pageNum, pageSize);
        // 查询符合条件的
        List<Recharge> rechargeList = purseService.getSelectedRecharge(email,status);
        // 参数：结果集合，连续要显示的页数
        PageInfo<Recharge> pageInfo = new PageInfo<Recharge>(rechargeList);
        // 将商品添加到页面
        model.addAttribute("info", pageInfo);
        model.addAttribute("_email", email);
        model.addAttribute("_status",status);
        return "admin/recharge_list";
    }

    /**
     * 批量删除充值记录
     * @param ids id列表
     * @return ResultInfo
     */
    @RequestMapping(value = "/recharge",method = RequestMethod.DELETE)
    @ResponseBody
    public ResultInfo deleteRechargeBatch(@RequestBody Integer[] ids){
        ResultInfo info = new ResultInfo();
        // 删除
        if (purseService.deleteRechargeBatch(ids)) {
            info.setFlag(true);
        }
        return info;
    }

    /**
     * 返回修改页面
     * @return admin/updatePassword
     */
    @RequestMapping(value = "/password",method = RequestMethod.GET)
    public String getPw(){
        return "admin/updatePassword";
    }

    /**
     * 修改密码
     * @return ResultInfo
     */
    @RequestMapping(value = "/password",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo updatePw(@RequestBody Admin admin){
        ResultInfo info = new ResultInfo();
        if(adminService.update(admin)){
            info.setFlag(true);
        }else{
            info.setErrorMsg("用户名或密码错误");
        }
        return info;
    }

    @RequestMapping(value = "/sys",method = RequestMethod.GET)
    public String sys(){
        return "admin/sysMsg";
    }

    @RequestMapping(value = "/sys",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo sys1(@RequestBody SystemMsg systemMsg){
        ResultInfo info = new ResultInfo();
        if(adminService.saveSys(systemMsg)){
            info.setFlag(true);
            info.setErrorMsg("发布成功");
        }else{
            info.setErrorMsg("请稍后重试");
        }
        return info;
    }

    /**
     * 获取所有加入黑名单的ip
     * @param model Model
     * @return
     */
    @RequestMapping(value = "/ipblack",method = RequestMethod.GET)
    public String ipBlack(Model model){
        List<String> ipBlackList = null;
        try {
            ipBlackList = IpUtil.getIpBlackList();
            model.addAttribute("ipList",ipBlackList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "admin/InterceptorIp";
    }

    /**
     * 添加黑名单ip
     * @param ip
     * @return
     */
    @RequestMapping(value = "/ipblack",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo addBlackIp(String ip){
        ResultInfo info = new ResultInfo();
        try {
            IpUtil.writeIp(ip);
            info.setFlag(true);
        } catch (IOException e) {
            info.setFlag(false);
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 添加黑名单ip
     * @param ip
     * @return
     */
    @RequestMapping(value = "/ipblack",method = RequestMethod.DELETE)
    @ResponseBody
    public ResultInfo delBlackIp(String ip){
        ResultInfo info = new ResultInfo();
        try {
            IpUtil.deleteElem(ip);
            info.setFlag(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }
}
